import * as fs from 'fs'
import * as path from 'path'
import * as crypto from 'crypto'
import { fileExt } from 'src/util'

/**
 * @param originalname 原始文件名(带文件后缀)
 * @example createTempChunkName('test.png', 1) => 'test.png.chunk1'
 */
export function chunkName(originalname: string, index: number) {
  return originalname + `.chunk${index}`
}

function chunkIndex(fileName: string) {
  const index = fileExt(fileName)!.match(/\d+/)![0] as string
  return Number(index)
}

/**
 * 升序 chunk
 */
export function sortChunk(a: string, b: string) {
  const indexA = chunkIndex(a)
  const indexB = chunkIndex(b)

  return indexA - indexB
}

/**
 * 找到当前文件的 所有 chunk 并 升序排序
 */
export function chunk(uploadPath: string) {
  return fs.readdirSync(uploadPath).sort(sortChunk)
}

/**
 * 递归删除文件
 */
export function deepRM(dir: string) {
  const files = fs.readdirSync(dir)

  while (files.length) {
    const temp = files.pop()!
    const stat = fs.statSync(path.join(dir, temp))

    if (stat.isDirectory()) {
      deepRM(dir)
      break
    }

    fs.rmSync(path.join(dir, temp))
  }

  fs.rmdirSync(dir)
}

export function md5(buffer: Buffer) {
  // 以md5的格式创建一个哈希值
  const hash = crypto.createHash('md5')
  return hash.update(buffer).digest('hex')
}
